#include "mainwindow.h"
#include "ui_mainwindow.h"


#define VID 0x154f
#define PID 0x4401

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    serialPortThread = new SerialPortThread();
}

MainWindow::~MainWindow()
{
    delete ui;

    delete serialPortThread;


}
void MainWindow::closeEvent(QCloseEvent *event)
{
    qDebug("软件退出");
    serialPortThread->stop();
    serialPortThread->wait();

    event->accept();
}
void MainWindow::on_pushButtonTest_clicked()
{
    serialPortThread->writeData();
    serialPortThread->start();
}
//static void print_devs(libusb_device **devs)
//{
//    libusb_device *dev;
//    int i = 0, j = 0;
//    uint8_t path[8];

//    while ((dev = devs[i++]) != NULL) {
//        struct libusb_device_descriptor desc;
//        int r = libusb_get_device_descriptor(dev, &desc);
//        if (r < 0) {
//            qDebug("failed to get device descriptor");
//            return;
//        }

//        qDebug("%04x:%04x (bus %d, device %d)",
//               desc.idVendor, desc.idProduct,
//               libusb_get_bus_number(dev), libusb_get_device_address(dev));

//        r = libusb_get_port_numbers(dev, path, sizeof(path));
//        if (r > 0) {
//            qDebug(" path: %d", path[0]);
//            for (j = 1; j < r; j++)
//                qDebug(".%d", path[j]);
//        }
//        qDebug("\n");
//    }
//}
void printfCharArray(const char *name,unsigned char *pBuf,int len){
    qDebug("Array %s start",name);
    for(int i=0;i<len;i++){
        printf("[%d]=%02x  ",i,pBuf[i]);
        if((i%10==0)&&(i>0)){
            printf("\n");
        }
    }
    qDebug("\nArray %s end",name);
}
void MainWindow::on_pushButtonUsb_clicked()
{
//    libusb_device **devs;
//    ssize_t cnt;
    int r;
    libusb_device_handle *dev_handle;

    r = libusb_init(NULL);
    if (r < 0){
        qCritical("libusb_init err = %d",r);
        return;
    }
    dev_handle = libusb_open_device_with_vid_pid(NULL,VID,PID);
    if(NULL == dev_handle){
        qCritical("libusb_open_device_with_vid_pid failed");
        return;
    }
    unsigned char buf[20] = {0xFE,0x00,0x02,0x0D,0x01,0x0C,0xEF};
    r=libusb_bulk_transfer(dev_handle,0x02,buf,7,NULL,1000);
    if(r < 0){
        qCritical("libusb_bulk_transfer write error=%d",r);
    }
    memset(buf,0,20);
    int rlen=0;
    r= libusb_bulk_transfer(dev_handle,0x81,buf,20,&rlen,1000);
    if(r < 0){
        qCritical("libusb_bulk_transfer read error=%d",r);
    }

    qDebug("read len = %d",rlen);
    printfCharArray("buf",buf,rlen);
    libusb_close(dev_handle);
//    cnt = libusb_get_device_list(NULL, &devs);
//    if (cnt < 0)
//        qDebug("libusb_get_device_list err = %d",cnt);

//    print_devs(devs);
//    libusb_free_device_list(devs, 1);

    libusb_exit(NULL);
}
